// pages/testPointsShop/index.js
Page({
  data: {
    shopList: [],
    loading: false,
    purchasing: false,
    envId: '',
    currentUser: ''
  },

  onLoad() {
    // 获取全局配置
    const app = getApp();
    this.setData({
      envId: app.globalData.env || '未配置',
      currentUser: app.globalData.openid ? app.globalData.openid.substring(0, 8) + '...' : '未获取'
    });
  },

  // 获取积分商城列表
  async getPointsShopList() {
    this.setData({ loading: true });
    
    try {
      console.log('开始获取积分商城列表');
      
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'getPointsShopList'
        }
      });
      
      console.log('获取积分商城列表结果:', result);
      
      if (result.result && result.result.success) {
        const shopList = result.result.data || [];
        
        this.setData({
          shopList: shopList
        });
        
        wx.showToast({
          title: `获取成功，共${result.result.total}个商品`,
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: result.result?.errMsg || '获取失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('获取积分商城列表失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 购买商品
  async purchaseItem(e) {
    const { index } = e.currentTarget.dataset;
    const shopItem = this.data.shopList[index];
    
    wx.showModal({
      title: '确认购买',
      content: `确定要购买"${shopItem.itemName}"吗？\n价格：${shopItem.price}积分`,
      confirmText: '购买',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ purchasing: true });
          
          try {
            console.log('开始购买商品:', shopItem._id);
            
            const result = await wx.cloud.callFunction({
              name: 'quickstartFunctions',
              data: {
                type: 'purchaseShopItem',
                shopItemId: shopItem._id
              }
            });
            
            console.log('购买结果:', result);
            
            if (result.result && result.result.success) {
              const { data } = result.result;
              
              wx.showModal({
                title: '购买成功',
                content: `${data.message}\n\n商品：${data.itemName}\n消耗积分：${data.price}\n剩余积分：${data.remainingPoints}`,
                showCancel: false
              });
            } else {
              wx.showToast({
                title: result.result?.errMsg || '购买失败',
                icon: 'error'
              });
            }
          } catch (error) {
            console.error('购买失败:', error);
            wx.showToast({
              title: '网络错误',
              icon: 'error'
            });
          } finally {
            this.setData({ purchasing: false });
          }
        }
      }
    });
  },

  // 复制商品信息到剪贴板
  copyShopInfo(e) {
    const { index } = e.currentTarget.dataset;
    const shopItem = this.data.shopList[index];
    
    const shopInfo = JSON.stringify(shopItem, null, 2);
    
    wx.setClipboardData({
      data: shopInfo,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 返回首页
  goBack() {
    wx.navigateBack();
  }
});
